﻿using ML.Entity;
using ML.IRepository;
using Dapper;
using System.Linq;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using System;

namespace ML.Repository
{
    /// <summary>
    /// 商户结算仓储实现类
    /// </summary>
    public class SettlementRepository : DBFactory, ISettlementRepository
    {
        public Pager<SettlementResponse> List(SettlementSearch settlementSearch)
        {
            //组装调用存储过程参数
            var criteria = new PageCriteria() { TableName = "ml_settlement s  INNER JOIN ml_merchant m ON s.MerchantId=m.Id" };
            if (!string.IsNullOrEmpty(settlementSearch.merchantid_search))
            {
                criteria.Conditions += string.Format(" AND m.Id='{0}'", settlementSearch.merchantid_search);
            }
            if (!string.IsNullOrEmpty(settlementSearch.merchantname_search))
            {
                criteria.Conditions += string.Format(" AND m.Name LIKE '%{0}%'", settlementSearch.merchantname_search);
            }
            if (!string.IsNullOrEmpty(settlementSearch.number_search))
            {
                criteria.Conditions += string.Format(" AND s.Number LIKE '%{0}%'", settlementSearch.number_search);
            }
            if (settlementSearch.settlementstatus_search != -1)
            {
                criteria.Conditions += string.Format(" AND s.SettlementStatus={0}", settlementSearch.settlementstatus_search);
            }
            criteria.PageIndex = settlementSearch.pageindex;
            criteria.Field = @"m.Name,s.*";
            criteria.PageSize = settlementSearch.pagesize;
            criteria.SortName = settlementSearch.ordername;
            if (settlementSearch.orderby)
            {
                criteria.Sort = "DESC";
            }
            else
            {
                criteria.Sort = "ASC";
            }

            //调用存储过程进行查询并且返回
            var list = GetPageData<SettlementResponse>(criteria);
            return list;
        }

        public SettlementEntity GetById(string id)
        {
            const string sql = @"SELECT* FROM ml_settlement WHERE Id=@Id";
            using (_db)
            {
                return _db.Query<SettlementEntity>(sql, new { @Id = id }).FirstOrDefault();
            }
        }

        public IEnumerable<SettlementEntity> GetSettlementByMerchantId(string merchantId)
        {
            const string sql = @"SELECT* FROM ml_settlement WHERE MerchantId=@MerchantId";
            using (_db)
            {
                return _db.Query<SettlementEntity>(sql, new { @MerchantId = merchantId });
            }
        }

        public bool Add(SettlementEntity entity)
        {
            const string sql = @"INSERT INTO ml_settlement(Id,MerchantId,ReceivablesId,Number,OrderAmount,CanSettlementAmount,ActSettlementAmount,
                    Creater,CreateTime,Optioner,SettlementStatus,SettlementTime,Remark)
                VALUES(@Id,@MerchantId,@ReceivablesId,@Number,@OrderAmount,@CanSettlementAmount,@ActSettlementAmount,@Creater,@CreateTime,
                    @Optioner,@SettlementStatus,@SettlementTime,@Remark)";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Update(SettlementEntity entity)
        {
            //todo，此sql含有问题
            const string sql = @"UPDATE ml_settlement SET OrderAmount=@OrderAmount,CanSettlementAmount=@CanSettlementAmount,ActSettlementAmount=@ActSettlementAmount,
	            Creater=@Creater,CreateTime=@CreateTime WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool UpdateSettlementStatuSucccess(string Id, SettlementEntity data, string Optioner)
        {
            const string update_settlement_sql = "UPDATE ml_settlement SET SettlementStatus=@SettlementStatus,Optioner=@Optioner,SettlementTime=@SettlementTime WHERE Id=@Id";
            const string update_capitalaccount_sql = "  UPDATE ml_capitalaccount SET Withdrawed = Withdrawed + @Withdrawed WHERE MerchantId = @MerchantId";
            using (var conn = OpenConnection())
            {
                MySqlTransaction trans = conn.BeginTransaction();
                var isUserTrue = conn.Execute(update_settlement_sql, new { @SettlementStatus = SettlementStatu.success, @Optioner = Optioner, @SettlementTime = DateTime.Now, @Id = Id }, trans);
                if (isUserTrue > 0)
                {
                    var isuserInvitationTrue = conn.Execute(update_capitalaccount_sql, new { @Withdrawed = data.ActSettlementAmount, @MerchantId = data.MerchantId }, trans);
                    if (isuserInvitationTrue < 0)
                    {
                        trans.Rollback();
                        return false;
                    }
                    trans.Commit();
                }
                else
                {
                    trans.Rollback();
                    return false;
                }
                return true;
            }
        }

        public bool UpdateSettlementStatu(string Id, int SettlementStatu, string Remark, string Optioner)
        {
            const string update_sql = "UPDATE ml_settlement SET SettlementStatus=@SettlementStatus,Remark=@Remark,Optioner=@Optioner,SettlementTime=@SettlementTime WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(update_sql, new { @SettlementStatus = SettlementStatu, @Remark = Remark, @Optioner = Optioner, @SettlementTime = DateTime.Now, @Id = Id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Delete(SettlementEntity entity)
        {
            throw new System.NotImplementedException();
        }

        public bool Delete(string id)
        {
            throw new System.NotImplementedException();
        }
    }
}